package com.qf.dao.impl;

import com.qf.dao.StuDao;
import com.qf.domain.Stu;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class StuDaoImpl implements StuDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public Stu selectByStuname(String stuname) {
        String sql = "select * from stuInfo where stuname=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Stu.class),stuname);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public long selectCount() {
        String sql = " select count(*) from stuInfo " ;
        try {
            return queryRunner.query(sql,new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Stu> selectByPage(int page_num, int page_size) {
        String sql = " SELECT * FROM stuInfo order by id LIMIT ?,?";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Stu.class),(page_num-1)*page_size,page_size);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(int id) {
        String sql = "  delete from stuInfo where id=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Stu selectById(int id) {
       String sql =" SELECT * FROM stuinfo WHERE id=? " ;
        try {
            return queryRunner.query(sql,new BeanHandler<>(Stu.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Stu stu) {
        String sql = " UPDATE stuInfo SET stuname=?,stuno=?,pwd=?,idcard=?,startdate=?,status=? WHERE id=?;\n ";
        Object[] params = {stu.getStuname(), stu.getStuno(), stu.getPwd(), stu.getIdcard(), stu.getStartdate(), stu.getStatus(), stu.getId()};
        try {
            queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
